package net.cathackers.devel.scmp.chat.impl.xmpp.iqhandlers;
import org.apache.log4j.Logger;

import net.cathackers.devel.scmp.auth.interfaces.UserID;
import net.cathackers.devel.scmp.chat.exceptions.RosterItemAlreadyExistsException;
import net.cathackers.devel.scmp.chat.exceptions.RosterItemNotFoundException;
import net.cathackers.devel.scmp.chat.impl.xmpp.iqcomponent.IQHandlerClassifierImpl;
import net.cathackers.devel.scmp.chat.impl.xmpp.iqcomponent.interfaces.IQHandler;
import net.cathackers.devel.scmp.chat.impl.xmpp.iqcomponent.interfaces.IQHandlerClassifier;
import net.cathackers.devel.scmp.chat.impl.xmpp.iqcomponent.roster.RosterProcessor;


import net.cathackers.devel.scmp.chat.interfaces.ChatManager;
import net.cathackers.devel.scmp.exceptions.BackendException;
import net.cathackers.devel.scmp.factories.SCMPFactory;

import net.cathackers.devel.scmp.xmpp.IQPacket;
import net.cathackers.devel.scmp.xmpp.Packet;
import net.cathackers.devel.scmp.xmpp.RosterPacket;
import net.cathackers.devel.scmp.xmpp.StanzaErrors;

public class RosterHandler extends IQHandler {

    private ChatManager chatManager_;
    private IQHandlerClassifier classifier_;
    private Logger logger_;

    public RosterHandler() {
	chatManager_ = SCMPFactory.getChatManager();
	classifier_ = new IQHandlerClassifierImpl("query", "jabber:iq:roster");
	logger_ = SCMPFactory.getLogger(this);
    }

    @Override
    public void process(IQPacket packet) {
	RosterPacket roster = new RosterPacket(packet);
	RosterProcessor processor = new RosterProcessor();
	Packet result;

	try {
	    switch (roster.getIQType()) {
	    case get:
		logger_.debug("Roster requested..");
		result = processor.resetRoster(roster);

		break;
	    case set:
		
		UserID from = roster.getFrom();
		String id   = roster.getID();
		processor.updateRoster(roster);
		result = processor.getReply(from, id);
		break;

	    default:
		result = processor.getErrorPacket(roster,
			StanzaErrors.Condition.unexpected_request);
		logger_.error("packet type must be get or set only .. ");

	    }

	} catch (RosterItemNotFoundException e) {
	    result = processor.getErrorPacket(roster,
		    StanzaErrors.Condition.forbidden);
	    logger_.error("the roster not found .. " + e.getMessage());
	} catch (RosterItemAlreadyExistsException e) {
	    result = processor.getErrorPacket(roster,
		    StanzaErrors.Condition.conflict);
	    logger_.error("the roster item already Exists .. ");
	}

	catch (BackendException e) {
	    result = processor.getErrorPacket(roster,
		    StanzaErrors.Condition.internal_server_error);
	    logger_.error("un expected error happened in the backend");
	}
        logger_.info("now we will deliver the result to the user");
	chatManager_.deliverToUser(result);
    }

    @Override
    public IQHandlerClassifier getClassifier() {
	return classifier_;
    }

}
